﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.ComponentModel;
using System.Collections.ObjectModel;
using Microsoft.Win32;
using System.IO;

namespace Freshome.m.vws
{
    /// <summary>
    /// Recipes.xaml 的交互逻辑
    /// </summary>
    public partial class Recipes : UserControl
    {
        private const string _ep = "wsHttp_IMultint";

        public Recipes()
        {
            InitializeComponent();
            this.topanel.Loaded += new RoutedEventHandler(topanel_Loaded);
        }

        void topanel_Loaded(object sender, RoutedEventArgs e)
        {
            var rps = this.DataContext as vms.Recipes;
            if (rps != null)
            {
                this.cbRecipe.Header = rps.Tellead;
            }
        }
        private void Recipe_CanExecute(object sender, CanExecuteRoutedEventArgs e)
        {
            var rps = this.DataContext as vms.Recipes;
            if (rps != null)
            {
                e.CanExecute = dgr.SelectedItem != null && rps.Enabled;
            }
            else e.CanExecute = false;
        }
        // 选择图片文件
        private void OpenImage_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            var rp = dgr.SelectedItem as mds.Recipe;
            if (rp != null)
            {
                OpenFileDialog dlg = new OpenFileDialog();
                dlg.Filter = "图片(*.PNG;*.JPG;*.GIF)|*.PNG;*.JPG;*.GIF";
                dlg.CheckFileExists = true;
                dlg.Multiselect = false;
                if (dlg.ShowDialog() == true)
                {
                    FileInfo fi = new FileInfo(dlg.FileName);
                    if (fi.Length > short.MaxValue)
                    {
                        MessageBox.Show(string.Format("只能保存{0}字节以下的图片！", short.MaxValue), "文件太大", MessageBoxButton.OK, MessageBoxImage.Warning);
                    }
                    else
                    {
                        rp.ImageType = fi.Extension.StartsWith(".") ? fi.Extension.Substring(1) : fi.Extension;
                        rp.ImageData = new byte[fi.Length];
                        using (FileStream fs = fi.OpenRead())
                        {
                            fs.Read(rp.ImageData, 0, (int)fs.Length);
                        }
                        rp.Bitmapped();
                    }
                }
            }
        }
        // delete recipe or steplan
        private void Delete_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            var dg = sender as DataGrid;
            var rps = this.DataContext as vms.Recipes;
            var r0 = dgr.SelectedItem as mds.Recipe;
            if (dg != null && r0 != null && rps != null)
            {
                string nm = Properties.Resources.ResourceManager.GetString(rps.Category.ToString());
                if (dg.Name == "dgr")
                {
                    if (r0.Created == false)
                    {
                        if (MessageBox.Show(string.Format("{0} 的数据将被删除，继续吗？", r0.Name), nm,
                            MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes)
                        {
                            rps.Helproxy.Syncall(cln =>
                            {
                                if (cln.DeleRecipe(r0.Raw.Mid)) rps.P_rps.Remove(r0);
                            }, new Rmt.MultintClient(_ep));
                        }
                    }
                    else rps.P_rps.Remove(r0);
                }
                else
                {
                    var r1 = dgp.SelectedItem as mds.Steplan;
                    if (r1 != null)
                    {
                        if (r1.Created == false)
                        {
                            if (MessageBox.Show(string.Format("{0} 的操作 {1} 将被删除，继续吗？", r0.Name, r1.Notes), nm,
                                MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes)
                            {
                                rps.Helproxy.Syncall(cln =>
                                {
                                    if (cln.DeleSteplan(r1.Raw.Mid)) r0.Steps.Remove(r1);
                                }, new Rmt.MultintClient(_ep));
                            }
                        }
                        else r0.Steps.Remove(r1);
                    }
                }
            }
        }
        private void Steplan_CanExecute(object sender, CanExecuteRoutedEventArgs e)
        {
            e.CanExecute = dgp.SelectedItem != null;
        }
        // 菜谱操作输入控制
        private void dgp_KeyDown(object sender, KeyEventArgs e)
        {
            DependencyObject dep = (DependencyObject)e.OriginalSource;
            if (dep != null && dep is TextBox)
            {
                while ((dep != null) && !(dep is DataGridCell))
                {
                    dep = VisualTreeHelper.GetParent(dep);
                }
                DataGridCell cell = dep as DataGridCell;
                if (cell != null)
                {
                    DataGridBoundColumn col = cell.Column as DataGridBoundColumn;
                    Binding binding = col.Binding as Binding;
                    if (binding.Path.Path == "Planum")
                    {   // 序号只允许数字
                        if ((e.Key >= Key.NumPad0 && e.Key <= Key.NumPad9) || e.Key == Key.Tab || e.Key == Key.Return || e.Key == Key.Enter ||
                            (e.Key >= Key.D0 && e.Key <= Key.D9 && e.KeyboardDevice.Modifiers != ModifierKeys.Shift))
                        {
                            e.Handled = false;
                        }
                        else e.Handled = true;
                    }
                }
            }
        }

        private void Find_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            var rps = this.DataContext as vms.Recipes;
            var r0 = dgr.SelectedItem as mds.Recipe;
            if (r0 != null && rps != null)
            {
                if (r0.Created || r0.Steps.Any(t => (t.IsValid && t.Created) || t.Updated))
                {
                    MessageBox.Show(string.Format("菜谱中发现未保存的修改，需要保存后才能继续！"), "保存菜谱及其制作", MessageBoxButton.OK, MessageBoxImage.Warning);
                }
                else
                {
                    Recipe dlg = new Recipe(r0.Mid, rps.Userole);
                    dlg.Owner = Application.Current.MainWindow;
                    dlg.ShowDialog();
                }
            }
        }
        private void Find_CanExecuted(object sender, CanExecuteRoutedEventArgs e)
        {
            var rps = this.DataContext as vms.Recipes;
            var r0 = dgr.SelectedItem as mds.Recipe;
            if (r0 != null && rps != null)
            {
                e.CanExecute = r0.IsValid && r0.Mid > default(short) && rps.Enabled;
            }
            else e.CanExecute = false;
        }
    }
}
